package org.zxt.web;

import lombok.extern.slf4j.Slf4j;
import org.zxt.web.buss.config.Conf;
import org.zxt.web.context.HealthRequestMapperHandler;
import org.zxt.web.context.StaticRequestMapperHandler;
import org.zxt.web.context.WebContext;
import org.zxt.web.nacos.NacosDiscoveryClient;
import org.zxt.web.nio.DefaultAsyncRunner;
import org.zxt.web.nio.IHTTPSession;
import org.zxt.web.nio.NioHTTPD;
import org.zxt.web.nio.Response;

@Slf4j
public class DefaultServlet extends NioHTTPD {

    private WebContext webContext;

    public DefaultServlet() throws Exception {
        super();
        this.webContext = new WebContext().setPkg("org.zxt.web.buss").start();
        Conf env = this.webContext.getBean("env");
        this.setAsyncRunner(new DefaultAsyncRunner(env.getInteger("server.httpd.cap"), env.getInteger("server.httpd.core"), env.getInteger("server.httpd.max"),env.getInteger("server.httpd.alive")));
        this.webContext.registeMappingHandlers(org.zxt.web.nio.Method.GET, StaticRequestMapperHandler.ROUTER, new StaticRequestMapperHandler(env.getString("server.resource-path")));
        this.webContext.registeMappingHandlers(org.zxt.web.nio.Method.GET, "/health", new HealthRequestMapperHandler());
    }

    public static void main(String[] args) throws Exception {
        DefaultServlet defaultServlet = new DefaultServlet();
        try {
            Conf env = defaultServlet.webContext.getBean("env");
            defaultServlet.serverStart(env.getString("server.host"), env.getIntValue("server.port"), NioHTTPD.SOCKET_READ_TIMEOUT, false);
            defaultServlet.webContext.registryNacos();
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                System.out.println("ShutdownHook executed.");
                defaultServlet.serverStop();
            }));
            log.info(" start server success port : http://{}:{}", env.getString("server.host"), env.getIntValue("server.port"));
        } catch (Exception ex) {
            ex.printStackTrace();
            if(defaultServlet!= null){
                defaultServlet.serverStop();
            }
        }
    }

    @Override
    public Response serve(IHTTPSession session) {
        return webContext.service(session);
    }

    @Override
    public void serverStop() {
        try{
            this.webContext.getBean(NacosDiscoveryClient.class).stop();
        } finally {
            super.serverStop();
        }
    }
}
